<template>
  <view>
    <view class="add-member page-content">
      <u-form label-position="top">
        <u-form-item
          label="选择用户"
          required
          v-if="formType === 'add'"
          class="u-m-b-20"
        >
          <view class="u-flex u-row-between">
            <u-input
              v-model="formData.userName"
              placeholder="请输入手机号"
            ></u-input>
            <u-button
              type="primary"
              @click="searchUser"
              size="medium"
              class="btn-p-40"
              >搜索</u-button
            >
          </view>
        </u-form-item>
        <view v-if="userInfo" class="userInfo">
          <view>姓名：{{ userInfo.name }}</view>
          <view class="u-m-b-10 u-m-t-10">手机号：{{ userInfo.mobile }}</view>
          <view>邮箱：{{ userInfo.email }}</view>
        </view>
        <u-form-item label="选择角色" required>
          <u-cell-item @click="roleChoose" style="padding: 0">
            {{
              chooseRoleInfo && chooseRoleInfo.length
                ? chooseRoleInfo.map((item: any) => item.label).join('，')
                : '请选择'
            }}</u-cell-item
          >
        </u-form-item>
      </u-form>
    </view>
    <u-button type="primary" @click="save" class="btn-box" :loading="loading"
      >确定</u-button
    >
    <multiple-select
      v-model="showRoleChoose"
      mode="single-column"
      :list="seleceList.roleList"
      :safe-area-inset-bottom="true"
      @confirm="confirm"
      :choosed="chooseRoleInfo"
      :init-choosed="true"
    >
      <template #content="{ data }: any"
        ><u-tag
          v-if="data.roleClass === 2"
          type="success"
          mode="dark"
          style="margin-left: 8px"
          text="自定义角色"
        ></u-tag
      ></template>
    </multiple-select>
  </view>
</template>
<script lang="ts" setup>
import {
  getRoleListSort,
  userPreciseQuery,
  saveOrgProjectUser,
  updateOrgProjectUserAuth,
} from '@/api/modules/project';
import { useUserStoreWidthOut } from '@/stores/user';
import multipleSelect from './multipleSelect.vue';
import { onLoad } from '@dcloudio/uni-app';
import { cellClick } from '@/hooks/useBack';
const formData = ref<any>({
  userName: '',
  roleId: '',
  roleList: [],
});
const seleceList = ref<any>({
  roleList: [],
});
const roleMarksMap = [
  '机构角色',
  '专业角色',
  '伦理委员会',
  'CRO',
  'SMO',
  '申办方',
  '其他',
];

const userStore: any = useUserStoreWidthOut();
// 获取所有角色
const getroleList = async () => {
  let res: any = await getRoleListSort({
    appId: userStore.appInfo ? userStore.appInfo.appId : '0',
    orgId: userStore.getOrgInfo.orgId,
    suitOrgType: 1,
    isProject: 0,
  });
  seleceList.value.roleList = res.map((item: any) => {
    return {
      value: item.roleId,
      label: item.roleMark
        ? `【${roleMarksMap[item.roleMark - 1]}】 ${item.roleName}`
        : item.roleName,
      roleId: item.roleId,
      roleName: item.roleName,
      roleClass: item.roleClass,
      roleMark: item.roleMark,
    };
  });
};
getroleList();
const showRoleChoose = ref(false);
const chooseRoleInfo = ref<any>();
const roleChoose = () => {
  showRoleChoose.value = true;
};
const confirm = (res: any) => {
  chooseRoleInfo.value = res;
  console.log(res);
};
const userInfo = ref<any>();
const searchUser = () => {
  userInfo.value = null;
  if (!formData.value.userName) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none',
      duration: 2000,
    });
    return;
  }
  userPreciseQuery(formData.value.userName).then((res: any) => {
    if (!res || !res.length) {
      uni.showToast({
        title: '没有查询到用户',
        icon: 'none',
        duration: 2000,
      });
      return;
    }
    userInfo.value = res[0];
  });
};
const loading = ref(false);
const save = async () => {
  if (!chooseRoleInfo.value || chooseRoleInfo.value.length == 0) {
    uni.showToast({
      title: '请选择角色',
      icon: 'none',
      duration: 2000,
    });
    return;
  }
  if (!userInfo.value) {
    uni.showToast({
      title: '请先搜索到用户',
      icon: 'none',
      duration: 2000,
    });
    return;
  }
  loading.value = true;
  const urlPath =
    formType.value === 'add' ? saveOrgProjectUser : updateOrgProjectUserAuth;
  try {
    await urlPath({
      appId: userStore.appInfo ? userStore.appInfo.appId : '0',
      orgId: userStore.getOrgInfo.orgId,
      userId: userInfo.value.userId,
      accountId: userInfo.value.accountId,
      projectId: projectId.value,
      userRoleList: chooseRoleInfo.value.map((item: any) => {
        return { roleId: item.value };
      }),
    });
    uni.showToast({
      title: '操作成功',
      icon: 'none',
      duration: 2000,
    });
    cellClick();
  } finally {
    loading.value = false;
  }
};
const projectId = ref('');
const formType = ref('add');
onLoad(() => {
  const {
    projectId: pId,
    formType: fType,
    userInfo: uInfo,
  } = (uni as any).$Router.getQuery();
  projectId.value = pId;
  formType.value = fType ? fType : 'add';
  console.log(uInfo, 'uInfo');
  if (fType === 'edit') {
    userInfo.value = uInfo;
    chooseRoleInfo.value =
      uInfo.userRoleList &&
      uInfo.userRoleList.map((item: any) => {
        return {
          value: item.roleId,
          label: item.roleMark
            ? `【${roleMarksMap[item.roleMark - 1]}】 ${item.roleName}`
            : item.roleName,
          roleId: item.roleId,
          roleName: item.roleName,
          roleClass: item.roleClass,
          roleMark: item.roleMark,
        };
      });
    uni.setNavigationBarTitle({
      title: '角色授权',
    });
  }
});
</script>
<style lang="scss">
.page-content {
  padding-bottom: calc(env(safe-area-inset-bottom) + 140rpx);
  width: 100%;
  height: 100%;
}
.btn-box {
  bottom: 0;
  width: 100%;
  background-color: #fff;
  padding: 20rpx;
  padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
  position: fixed;
  z-index: 10;
  box-sizing: border-box;
}
.userInfo {
  background: #f3f8fd;
  padding: 10px 15px;
  border-radius: 5px;
}
.u-form {
  background: #fff;
  padding: 20rpx 40rpx;
  .u-cell {
    padding: 0 !important;
  }
}
</style>
